<?php

// make all file including functions use the one 'load' function.
class Tyh_Loader
{	
	private static $instance;
	
	protected $models = array();
	protected $controllers = array();
	protected $libraries = array();
	protected $autoloaded = FALSE;
	protected $loaded = FALSE;

	
	public function view($filename, $data = array(), $enable_buffer = FALSE, $echo = TRUE, $ext = 'php')
	{
		$filename = TYH_APPPATH . 'views' . DIRECTORY_SEPARATOR . $filename . '.' . $ext;
		
		if( $enable_buffer === TRUE)
		{
			ob_start();
			$this->load($filename, $data);			
			$content = ob_get_clean();
			if( $echo )
			{
				echo $content;
			}
			else
			{
				return $content;
			}			
		}
		
		return $this->load($filename, $data);
	}

	public function model($filename, $ext = 'model.php')
	{
		// TODO: find a way to pass vars through the constructor of a model
		
		$file = TYH_APPPATH . 'models' . DIRECTORY_SEPARATOR . $filename . '.' . $ext;
		$this->load($file);
		
		// build the correct class name for instantiation
		$r = str_replace($ext, '', $filename);
		$r = explode('-', $r);
		$classname = '';
		$last_key = end($r);
		foreach($r as $part)
		{						
			$classname .= ($part != $last_key) ? ucfirst($part) . '_' : ucfirst($part) ;
		}
		
		$tyh = tyh_get_instance();

		// see above comment in this class
		$classname = $tyh->config->get('prefix') . '_' . $classname . '_Model';
		
		// only create a new instance if it's not already been instantiated
		if( class_exists($classname) && !array_key_exists( $classname, $this->models) )
		{	
			// create a new instance of the class
			return $this->models[$classname] =& new $classname();
		}
		else if(array_key_exists( $classname, $this->models))
		{
			return $this->models[$classname];
		}
		else
		{
//			$tyh->error($msg); TODO: include a central error handler (prevents use of is_debug_on flag)
			
			if( $tyh->is_debug_on())
			{
				trigger_error( __( 'Class: ' . $classname . ' does not exists' ) );
			}
			
			return FALSE;
		}
	}
	
	// TODO: fix this function, why?
	public function library($filename, $ext = 'php')
	{
		$filename = TYH_APPPATH . 'libraries/' . $filename . '.' . $ext;
				
		return $this->load($filename);
		
		/*
		// only create a new instance if it's not already been instantiated
		if( class_exists($classname) && !array_key_exists( $classname, $this->libraries) )
		{						
			// create a new instance of the class
			return $this->libraries[$classname] =& new $classname();
		}
		else if(array_key_exists( $classname, $this->libraries))
		{
			return $this->libraries[$classname];
		}
		else
		{
//			$tyh->error($msg); TODO: include a central error handler (prevents use of is_debug_on flag)
			$tyh =& tyh_get_instance();
			
			if( $tyh->is_debug_on())
			{
				trigger_error( __( 'Class: ' . $classname . ' does not exists' ) );
			}
			
			return FALSE;
		}
		*/
	}
	
	protected function load( $filename, $data = array())
	{
		if( !file_exists( $filename ) )
		{
			trigger_error( __( 'File: ' . $filename . ' does not exist' ) );
			
			return FALSE;
		}
		
		if(!empty($data))
			extract($data);
		
		include_once($filename);
		
		return TRUE;
	}	
	
	// function name should be loadControllers
	// and use autoload for autoloading files that are defined in app/config/config.php $config->autoload
	public function autoload()
	{		
		if( $this->autoloaded )
			return;
		
		$config =& Tyh_Config::getInstance();
		
		// /*
		// scan controller dir
		$filenames = scandir(TYH_APPPATH . 'controllers/');
		
		// loop through each found file
		foreach($filenames as $filename)
		{
			// check if filename contains .controller
			$r = strstr($filename, '.controller.php');
			if( $r !== FALSE)
			{
				$file = TYH_APPPATH . 'controllers/' . $filename;
				
				// check if it is a file
				if( is_file( $file ) )
				{
					include_once($file);					
					
					// build the correct class name for instantiation
					$r = str_replace('.controller.php', '', $filename);
					$r = explode('-', $r);
					$classname = '';
					$last_key = end($r);
					foreach($r as $part)
					{						
						$classname .= ($part != $last_key) ? ucfirst($part) . '_' : ucfirst($part) ;
					}
					
					$classname = $config->get('prefix') . '_' . $classname . '_Controller';
					
					// only create a new instance if it's not already been instantiated
					if( class_exists($classname) && !array_key_exists( $classname, $this->controllers) )
					{
						$this->autoloaded = TRUE;
						// create a new instance of the class
						$this->controllers[$classname] =& new $classname();
					}
					else 
					{
						$tyh = tyh_get_instance();
						
						if( $tyh->is_debug_on() )
						{
							trigger_error( _x( 'Class does not exist. Class: "', TYH_LANG_CONTEXT ) . $classname . '"' );
						}
						
						return FALSE;
					}
				}
			}
		}
		// */
		
		// make sure function autoload runs once
		$this->autoloaded = TRUE;
	}
	
	public function autoLoader()
	{
		// TODO: include files, add objects to controller (helper, library), add property autoloaded to config(?)
		
		if( $this->loaded )
			return;
		
		$tyh = tyh_get_instance();
		
		include(TYH_APPPATH . 'config/autoload.php');
		// TODO: rename this property to a more symantic one
		$this->loaded = TRUE;
		
		if( !isset( $autoload ) )
			return;
		
		// load custom config file
		if( isset( $autoload->config ) && is_array( $autoload->config ) )
		{
			foreach( $autoload->config as $filename )
			{
				$tyh->config->load($filename);
			}
		}
		
		// autoload helpers and libraries
		$types = array('helper', 'library');
		
		foreach($types as $type)
		{
			if( isset( $autoload->$type ) )
			{
				foreach ( $autoload->$type as $filename )
				{
					$this->$type($filename);
				}
			}
		}		
	}
	
	public function helper( $file, $ext = 'php' )
	{
		$filename = TYH_APPPATH . 'helpers/' . $file . '.' . $ext;
		
		return $this->load($filename);
	}
	
	public static function getInstance()
	{		
		if( !isset(self::$instance) )
		{
			self::$instance = new self();
		}
		
		return self::$instance;
	}
}